from fastapi import APIRouter, HTTPException, Depends
from app.schemas.video_schemas import (
    ImageGenerateRequest,
    ImageGenerateResponse, 
    VideoGenerateRequest,
    VideoGenerateResponse,
    TemplateToVideoRequest,
    TemplateToVideoResponse,
    TaskStatusResponse
)
from app.services.ai_manager import ai_service_manager
from app.services.ai_base import GenerationRequest, AIServiceType, AIServiceProvider
from .video_service import (
    check_user_quota,
    update_quota_usage,
    get_status_message
)
from app.tasks.generation_tasks import generate_video_async
from app.tasks.template_video_tasks import generate_template_to_video_async
from app.tasks.image_generation_tasks import generate_image_async
from app.celery_app import celery_app
import logging

logger = logging.getLogger(__name__)
router = APIRouter()

# ============================================================================
# 图片生成接口 (包括以图生图)
# ============================================================================

@router.post("/v1/image/generate", response_model=ImageGenerateResponse)
async def generate_image(
    request: ImageGenerateRequest,
    user_id: int = 1  # TODO: 从JWT token中获取真实user_id
):
    """
    图片生成接口
    - 纯文本生图：只填prompt和aspect_ratio等基础参数
    - 模板生图：提供template_image_url + user_image_url，将两张图片融合
    """
    try:
        # 判断是否为以图生图模式 (有template_image_url就是以图生图)
        is_template_mode = bool(
            request.template_image_url or request.template_image_base64
        )
        mode_desc = "以图生图(图片编辑)" if is_template_mode else "文本生图"
        
        logger.info(f"收到图片生成请求 - 用户: {user_id}, 模式: {mode_desc}")
        
        # 构建请求参数
        params = {
            "prompt": request.prompt,
            "aspect_ratio": request.aspect_ratio.value if request.aspect_ratio else "16:9",
            "style": request.style.value if request.style else "realistic",
            "seed": request.seed,
            "generation_type": "template_fusion" if is_template_mode else "text_to_image"
        }
        
        if is_template_mode:
            params.update({
                "template_image_url": request.template_image_url,
                "template_image_base64": request.template_image_base64,
                "user_image_url": request.user_image_url,
                "user_image_base64": request.user_image_base64,
                "fusion_strength": request.fusion_strength
            })
        
        # 检查用户配额 (简化版)
        quota_check = {"can_proceed": True}  # TODO: 实现真实的配额检查
        if not quota_check.get("can_proceed", True):
            raise HTTPException(
                status_code=402,
                detail=quota_check.get("message", "配额不足，请充值后重试")
            )
        
        # 提交到异步队列
        task = generate_image_async.delay(
            request.dict(),
            user_id,
            params
        )
        
        logger.info(f"图片生成任务已提交 - 任务ID: {task.id}")
        
        response = ImageGenerateResponse(
            success=True,
            task_id=task.id,
            image_url=None,  # 处理中
            cost=0.0,  # 处理完成后更新
            status="queued",
            message=f"{mode_desc}任务已加入队列...",
            aspect_ratio=request.aspect_ratio.value if request.aspect_ratio else None
        )
        
        return response
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"图片生成请求异常: {str(e)}")
        return ImageGenerateResponse(
            success=False,
            error_message=f"服务器内部错误: {str(e)}",
            aspect_ratio=request.aspect_ratio.value if request.aspect_ratio else None,
            status="failed"
        )

# ============================================================================
# 视频生成接口 (包括图片转视频)
# ============================================================================

@router.post("/v1/video/generate", response_model=VideoGenerateResponse)
async def generate_video(
    request: VideoGenerateRequest,
    user_id: int = 1  # TODO: 从JWT token中获取真实user_id
):
    """
    视频生成接口 - 支持2种模式
    1. 纯文本生视频：只填prompt和duration等基础参数
    2. 图片转视频：提供source_image_url (通常是图片生成接口的输出)
    """
    try:
        # 判断生成模式
        is_image_to_video = bool(request.source_image_url or request.source_image_base64)
        
        if is_image_to_video:
            mode_desc = "图片转视频"
            generation_type = "image_to_video"
        else:
            mode_desc = "文本生视频"
            generation_type = "text_to_video"
        
        logger.info(f"收到视频生成请求 - 用户: {user_id}, 模式: {mode_desc}")
        
        # 构建请求参数
        params = {
            "prompt": request.prompt,
            "duration": request.duration,
            "aspect_ratio": request.aspect_ratio.value if request.aspect_ratio else "16:9",
            "resolution": request.resolution.value if request.resolution else "720p",
            "style": request.style.value if request.style else "realistic",
            "seed": request.seed,
            "generation_type": generation_type,
            "image_strength": request.image_strength
        }
        
        # 添加图片转视频参数
        if is_image_to_video:
            params.update({
                "source_image_url": request.source_image_url,
                "source_image_base64": request.source_image_base64
            })
        
        # 检查用户配额
        quota_check = await check_user_quota(user_id, params)
        if not quota_check.get("can_proceed", True):
            raise HTTPException(
                status_code=402,
                detail=quota_check.get("message", "配额不足，请充值后重试")
            )
        
        # 提交到Celery异步队列
        task = generate_video_async.delay(
            request.dict(), 
            user_id, 
            params
        )
        
        logger.info(f"视频生成任务已提交到队列 - 任务ID: {task.id}")
        
        response = VideoGenerateResponse(
            success=True,
            task_id=task.id,
            video_url=None,
            cost=0.0,
            estimated_time=300,
            generation_type=generation_type,
            aspect_ratio=request.aspect_ratio.value if request.aspect_ratio else None,
            duration=request.duration,
            status="queued",
            message=f"{mode_desc}任务已加入队列..."
        )
        
        return response
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"视频生成请求异常: {str(e)}")
        return VideoGenerateResponse(
            success=False,
            error_message=f"服务器内部错误: {str(e)}",
            generation_type="unknown",
            aspect_ratio=request.aspect_ratio.value if request.aspect_ratio else None,
            duration=request.duration,
            status="failed"
        )

# ============================================================================
# 组合流程接口 - 模板生视频一站式接口  
# ============================================================================

@router.post("/v1/template-to-video/generate", response_model=TemplateToVideoResponse)
async def generate_template_to_video(
    request: TemplateToVideoRequest,
    user_id: int = 1  # TODO: 从JWT token中获取真实user_id
):
    """
    模板生视频一站式接口
    用户只需提供：模板图片 + 普通图片 + 提示词
    自动完成：1. 图片融合 → 2. 图片转视频
    """
    try:
        logger.info(f"收到模板生视频请求 - 用户: {user_id}")
        logger.info(f"模板图片: {request.template_image_url}")
        logger.info(f"用户图片: {request.user_image_url}")
        
        # 构建组合流程参数
        params = {
            # 第一步：图片融合参数
            "template_image_url": request.template_image_url,
            "user_image_url": request.user_image_url,
            "template_image_base64": request.template_image_base64,
            "user_image_base64": request.user_image_base64,
            "image_prompt": request.image_prompt or request.prompt,
            "fusion_strength": request.fusion_strength,
            
            # 第二步：视频生成参数
            "video_prompt": request.prompt,
            "duration": request.duration,
            "aspect_ratio": request.aspect_ratio.value if request.aspect_ratio else "16:9",
            "resolution": request.resolution.value if request.resolution else "720p",
            "style": request.style.value if request.style else "realistic",
            "image_strength": request.image_strength,
            "seed": request.seed,
            
            # 流程标识
            "generation_type": "template_to_video_combined"
        }
        
        # 检查用户配额 (需要考虑两步的成本)
        quota_check = {"can_proceed": True}  # TODO: 实现组合流程的配额检查
        if not quota_check.get("can_proceed", True):
            raise HTTPException(
                status_code=402,
                detail=quota_check.get("message", "配额不足，请充值后重试")
            )
        
        # 提交到异步队列
        task = generate_template_to_video_async.delay(
            request.dict(),
            user_id, 
            params
        )
        
        logger.info(f"模板生视频任务已提交 - 任务ID: {task.id}")
        
        response = TemplateToVideoResponse(
            success=True,
            task_id=task.id,
            video_url=None,
            intermediate_image_url=None,
            total_cost=0.0,
            estimated_time=600,  # 组合流程需要更长时间
            status="queued",
            message="模板生视频任务已加入队列，将分步骤执行：1.图片融合 → 2.视频生成",
            current_step="等待开始",
            aspect_ratio=request.aspect_ratio.value if request.aspect_ratio else None,
            duration=request.duration
        )
        
        logger.info(f"模板生视频任务响应: {response}")
        return response
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"模板生视频请求异常: {str(e)}")
        return TemplateToVideoResponse(
            success=False,
            error_message=f"服务器内部错误: {str(e)}",
            aspect_ratio=request.aspect_ratio.value if request.aspect_ratio else None,
            duration=request.duration,
            status="failed"
        )

# ============================================================================
# 任务状态查询接口
# ============================================================================

@router.get("/v1/task/{task_id}/status", response_model=TaskStatusResponse)
async def get_task_status(task_id: str):
    """
    通用任务状态查询接口
    支持图片生成、视频生成、模板视频生成的状态查询
    """
    try:
        logger.info(f"查询任务状态: {task_id}")
        
        # 所有任务都通过Celery查询
        from celery.result import AsyncResult
        
        celery_task = AsyncResult(task_id, app=celery_app)
        
        if not celery_task:
            raise HTTPException(status_code=404, detail="Task not found")
        
        # 根据Celery任务状态返回
        if celery_task.state == "PENDING":
            return TaskStatusResponse(
                task_id=task_id,
                status="queued",
                message="任务等待中"
            )
        elif celery_task.state == "PROGRESS":
            task_info = celery_task.info or {}
            return TaskStatusResponse(
                task_id=task_id,
                status="processing", 
                progress=task_info.get('progress', 0),
                message=task_info.get('message', '处理中...')
            )
        elif celery_task.state == "SUCCESS":
            result = celery_task.result
            
            # 判断任务类型并返回相应结果
            if result.get('generation_type') == 'template_to_video_combined':
                # 模板生视频任务
                return TaskStatusResponse(
                    task_id=task_id,
                    status="completed",
                    result_url=result.get('video_url'),
                    cost=result.get('total_cost'),
                    message="模板生视频完成"
                )
            elif result.get('image_url'):
                # 图片生成任务
                return TaskStatusResponse(
                    task_id=task_id,
                    status="completed",
                    result_url=result.get('image_url'),
                    cost=result.get('cost'),
                    message="图片生成完成"
                )
            else:
                # 普通视频生成任务
                return TaskStatusResponse(
                    task_id=task_id,
                    status="completed",
                    result_url=result.get('video_url'),
                    cost=result.get('cost'),
                    message="视频生成完成"
                )
        else:  # FAILURE
            # 安全处理失败任务的错误信息
            try:
                error_info = celery_task.info
                if isinstance(error_info, dict):
                    error_message = error_info.get('error', str(error_info))
                else:
                    error_message = str(error_info) if error_info else "任务执行失败"
            except Exception:
                error_message = "任务执行失败（无法获取详细错误信息）"
            
            return TaskStatusResponse(
                task_id=task_id,
                status="failed",
                error=error_message,
                message="任务执行失败"
            )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"查询任务状态异常: {str(e)}")
        raise HTTPException(status_code=500, detail=f"查询任务状态失败: {str(e)}")


